package vip.ola.pay.batchpay.jisubatchpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.constant.PayConstant;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.channel.BaseTrans;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static vip.ola.core.common.constant.PayEnum.ERR_0121;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
@Service
public class QuickPayTransService extends BaseTrans {

    private static final MyLog _log = MyLog.getLog(QuickPayTransService.class);

    @Override
    public String getChannelName() {
        return PayConstant.CHANNEL_NAME_ALIPAY;
    }

    public JSONObject trans(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        try {
            _log.info("代付转账：" + transOrder.getChannelMchId());
            AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(transOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            String orderId = transOrder.getTransOrderId();
            String payUrl = accountParams.getString("payUrl");
            String privateKey = accountParams.getString("privateKey");
            String pay_notifyurl=accountParams.getString("notify_url");
            Map<String,Object> map = new HashMap<>();
            map.put("merchant_id",Long.valueOf(mchId));
            map.put("remit_type",1L);
            map.put("order_no",orderId);
            map.put("device_type",1);
            map.put("payee_name", transOrder.getAccountName().trim());
            map.put("payee_card_no", transOrder.getAccountNo().trim());
            if ("广东发展银行".equals(transOrder.getBankName())){
                map.put("payee_bank_name", "⼴发银⾏");
            }else if ("上海农村商业银行".equals(transOrder.getBankName())){
                map.put("payee_bank_name", "上海农商银⾏");
            }else {
                map.put("payee_bank_name", transOrder.getBankName());
            }
            map.put("order_amount",transOrder.getAmount());
            map.put("notify_url",pay_notifyurl);
            Long time = System.currentTimeMillis()/1000;
            map.put("create_time",time.intValue());
            map.put("sign",getSign(map,privateKey));
            map.put("user_id",UUID.randomUUID().toString());
            map.put("user_ip","159.138.11.127");
            _log.info("下单请求={}",JSONObject.toJSONString(map));
            String respData = call(payUrl,map);
            _log.info("下单返回={}",respData);
            JSONObject jsonObject = JSONObject.parseObject(respData);
            retObj.put("transOrderId", transOrder.getTransOrderId());
            if (jsonObject != null){
                String status = jsonObject.getString("status");
                if ( "1".equals(status) ){
                    retObj.put("status",1);
                }else {
                    retObj.put("status",3);
                    retObj.put("channelErrCode", status);
                    retObj.put("channelErrCode", jsonObject.getString("text"));
                }
            }else {
                retObj.put("status",3);
            }

        } catch (Exception e) {
            e.printStackTrace();
            retObj.put("status",3);
            retObj.put("channelErrCode", e.getMessage());
        }
        return  retObj;
    }


    private String getSign(Map<String,Object> object, String privateKey) {
        Long merchantId = (Long) object.get("merchant_id");
        String orderNo = (String) object.get("order_no");
        Long payType = (Long) object.get("remit_type");
        Long orderAmount = (Long) object.get("order_amount");
        String notifyUrl = (String) object.get("notify_url");
        Integer createTime = (Integer) object.get("create_time");
        StringBuffer sb = new StringBuffer();
        sb.append(merchantId).append(orderNo).append(payType).append(orderAmount).append(notifyUrl).append(createTime).append(privateKey);
        return PayDigestUtil.md5((sb.toString()),"UTF-8");
    }


    public static String call(String url, Map param) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }



    public JSONObject query(TransOrder transOrder) {
//        JSONObject retObj = buildRetObj();
//        retObj.put("transOrderId", transOrder.getTransOrderId());
//        try {
//            Map<String, String> obj = new HashMap<>();
//            obj.put("merchantOrderNo", transOrder.getTransOrderId());
//            String response=callGet("https://pay.fhpay.pro/order/cashierQuery",obj);
//            _log.info("查询结束respData->{}",response);
//            JSONObject jsonObject = JSONObject.parseObject(response);
//            if (jsonObject != null){
//                String code = jsonObject.getString("code");
//                if ("200".equals(code)){
//                    JSONObject dataObject =JSONObject.parseObject(jsonObject.getString("data"));
//                    if (dataObject!= null && "1".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 2);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else if (dataObject!= null && "0".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 1);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else if (dataObject!= null && "2".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 3);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else if (dataObject!= null && "3".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 2);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else {
//                        retObj.put("status", 1);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }
//                }else {
//                    retObj.put("status", 1);
//                    retObj.put("channelErrCode", code);
//                    retObj.put("channelErrCode", jsonObject.getString("msg"));
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return  null;
    }



    @Override
    public JSONObject balance(String payParam) {
        return null;
    }



}
